import { Popconfirm, Button, message, Table, Switch } from 'antd'
import services from '@/services'
import { CodeRuleType } from '@/services/features/code-join-groups'
import type { CodeRule } from '@/services/features/code-join-groups'
import EditModal from '../edit'
import './index.module.less'

export default function CodeList() {
  const [rules, setRules] = useState<CodeRule[]>([])
  const [loading, setLoading] = useState(false)
  const loadRules = useCallback(async () => {
    setLoading(true)
    const res = await services.features.codeJoinGroups.load()
    if (res.success) setRules(res.data)
    else void message.warning('口令进群规则加载失败')
    setLoading(false)
    return res.success
  }, [])

  const [switching, setSwitching] = useState(false)
  const switchStatus = useCallback(
    async (rule: CodeRule) => {
      setSwitching(true)

      const res = await services.features.codeJoinGroups.addOrUpdate({
        ...rule,
        enable: !rule.enable,
      })
      if (res.success) void message.success('操作成功')
      else void message.warning(`操作失败：${res.error}`)

      await loadRules()

      setSwitching(false)
    },
    [loadRules],
  )

  const [removing, setRemoving] = useState(false)
  const remove = useCallback(
    async (id: number) => {
      setRemoving(true)

      const res = await services.features.codeJoinGroups.remove(id)
      if (res.success) void message.success('删除成功')
      else void message.warning(`删除失败：${res.error}`)

      await loadRules()

      setRemoving(false)
    },
    [loadRules],
  )

  const [editing, setEditing] = useState<false | true | CodeRule>(false) // true: 新建  CodeRule: 编辑
  const finishEdit = useCallback(() => {
    setEditing(false)
    void loadRules()
  }, [loadRules])

  const blocking = loading || removing || switching

  useEffect(() => {
    void loadRules()
  }, [loadRules])

  const renderPreview = useCallback((rule: CodeRule) => {
    return <>
      <div>{getTypeDescribe(rule.type)}</div>
      <div styleName="keyword">{rule.keyword}</div>
    </>
  }, [])

  const renderStatus = useCallback(
    (rule: CodeRule) => {
      return <Switch
        checked={rule.enable}
        onChange={async () => switchStatus(rule)}
        checkedChildren="开"
        unCheckedChildren="关"
      />
    },
    [switchStatus],
  )

  const renderActions = useCallback(
    (rule: CodeRule) => {
      return <>
        <Button type="link" onClick={() => setEditing(rule)}>
          修改
        </Button>
        <Popconfirm title="确定要删除此规则吗？" onConfirm={async () => remove(rule.id)}>
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>
      </>
    },
    [remove],
  )

  return <div styleName="content">
    <header>
      <Button disabled={blocking} type="primary" onClick={() => setEditing(true)}>
        新建口令进群
      </Button>
    </header>

    <Table<CodeRule>
      rowKey="id"
      dataSource={rules}
      scroll={{ y: 300 }}
      pagination={false}
      loading={blocking}
    >
      <Table.Column<CodeRule>
        title="口令规则名称"
        key="name"
        width={180}
        styleName="name"
        dataIndex="name"
      />
      <Table.Column<CodeRule>
        title="口令内容"
        key="keyword"
        styleName="preview"
        render={renderPreview}
      />
      <Table.Column<CodeRule> title="状态" key="status" styleName="status" render={renderStatus} />
      <Table.Column<CodeRule>
        title="操作"
        key="actions"
        width={140}
        styleName="actions"
        render={renderActions}
      />
    </Table>

    <EditModal editing={editing} onFinish={finishEdit} />
  </div>
}

function getTypeDescribe(type: CodeRuleType) {
  return {
    [CodeRuleType.Exact]: '精确匹配',
    [CodeRuleType.Fuzzy]: '包含匹配',
    [CodeRuleType.Regex]: '正则匹配',
  }[type]
}
